package com.zhf.cloud.gateway.springcloudgateway.logback.mongodb;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.mongodb.BasicDBObject;
import org.slf4j.MDC;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;

/**
 * @author: 曾鸿发
 * @create: 2021-11-22 12:28
 * @description：
 **/
public class JvMongoDBAppender  extends UnsynchronizedAppenderBase<ILoggingEvent> {

    @Override
    protected void append(ILoggingEvent eventObject) {
        if(ApplicationContextProvider.getApplicationContext()==null){
            return;
        }
        MongoTemplate mongoTemplate = ApplicationContextProvider.getBean(MongoTemplate.class);
        if (mongoTemplate != null) {
            final BasicDBObject doc = new BasicDBObject();
            String traceid = MDC.get("traceid");
            if (traceid == null) {
                traceid = "-";
            }
            doc.append("traceid", traceid);
            doc.append("level", eventObject.getLevel().toString());
            doc.append("service", ApplicationContextProvider.getApplicationContext().getId());
            doc.append("timestamp", new Date(eventObject.getTimeStamp()));
            doc.append("message", eventObject.getFormattedMessage());
            doc.append("logger", eventObject.getLoggerName());
            doc.append("thread", eventObject.getThreadName());
            doc.append("pid", getPid());
            doc.append("ip", getIp());
            Map<String, String> data = eventObject.getMDCPropertyMap();
            for (String key : data.keySet()) {
                doc.append(key, data.get(key));
            }
            IThrowableProxy throwableProxy = eventObject.getThrowableProxy();
            if (throwableProxy != null) {
                ThrowableProxy tbp = (ThrowableProxy) throwableProxy;
                if (tbp != null) {
                    doc.append("errorinfo", getErrmessage(tbp.getThrowable()));
                }
            } else {
                //logEntry.append("errorinfo", "");
            }

//
//      doc.append("level", eventObject.getLevel().toString());
//      doc.append("logger", eventObject.getLoggerName());
//      doc.append("thread", eventObject.getThreadName());
//      doc.append("message", eventObject.getFormattedMessage());
            mongoTemplate.insert(doc, "log");
        }
    }

    private String getIp(){
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return "UNKNOW_HOST";
        }
    }
    private String getPid(){
        return ManagementFactory.getRuntimeMXBean().getName();
    }


    public static String getErrmessage(Throwable t){
        if(t==null)
            return "";
        StringWriter stringWriter=new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter,true));
        return stringWriter.getBuffer().toString();
    }
}

